<template>
  <scroll-view class="maintenanceStatistics" @scrolltolower="scrolltolower" @scroll="scrollEvent"
               :style="{ height: pageHight + 'px' }" :scroll-y="true" scroll-with-animation>
    <view class="" @click="handlerClick">

      <view class="head">
        <Header @filter="filterFuc" @clickuser="toMine" @toNext="handleBack" :tabIdx="headerIndex"
                :shadow="false" :filterList="filterList" :myElevator="true" :mainPlan="mainPlan"
                :customDate="customDate"></Header>
        <view v-if="scoreState !== 1" class="left">
          <uni-search-bar :radius="10" v-model="obj.keyword" :disabled="false" clearButton="always"
                          placeholder="请输入项目/电梯关键词" @blurs="handleReSet" />

          <filterModel v-if="showFilter" :all="allFilter" :mainPlan="mainPlan" :buildingId="buildingId"
                       :csd="csd" @filterd="filterd" :userIds="obj.userIds"
                       :date="{ startTime: this.beginTime || formatTime(getMonthDate().startDate), endTime: this.endTime || formatTime(getMonthDate().endDate), keyword: this.obj.keyword }"
                       style="width: 100%;"></filterModel>
        </view>
        <view class="setp" v-if="mainPlan === 1">
          <view class="setp_cont">共 <text style="color:#0091FF;">{{ eleObjs.elevatorCount }}</text> 台梯（<text
              style="color:#0091FF;">{{ eleObjs.planTaskCount }}</text>个任务）</view>
          <view class="setp_LR">
            <view class="L_text">
              <view class="text_tit">保养进度</view>
              <view class="tipsr">
                <zb-tooltip placement="bottom-start" ref="tooltip1" class="tipStyle">
                  <uni-icons color="#999" style="margin:0 2rpx" type="help" />
                  <view class="" slot="content">
                    <view class="">任务已维保签字的进度</view>
                  </view>
                </zb-tooltip>
                <!-- <uni-icons color="#999" style="margin:0 2rpx" type="help" />
                <view class="tips_text"  v-if="isTipsOne">
                  任务已维保签字的进度
                </view> -->
              </view>
              <view style="width:200rpx;">
                <ai-progress :percentage="(eleObjs.maintainSignatureCount / eleObjs.planTaskCount * 100)"
                             :isCount="(eleObjs.maintainSignatureCount || 0) + '/' + (eleObjs.planTaskCount || 0)"
                             :strokeWidth="6" inBgColor="#DCF0FF" bgColor="#0091FF">
                </ai-progress>
              </view>
            </view>
            <view class="R_text">
              <view class="text_tit">客户签字进度</view>
              <view class="tipsr">
                <zb-tooltip placement="bottom" ref="tooltip2" class="tipStyle">
                  <uni-icons color="#999" style="margin:0 2rpx" type="help" />
                  <view class="" slot="content">
                    <view class="">任务已客户签字的进度</view>
                  </view>
                </zb-tooltip>
                <!-- <uni-icons color="#999" style="margin:0 2rpx" type="help" />
                <view class="tips_text" style="left: 350rpx;"  v-if="isTipsTwo">
                  任务已客户签字的进度
                </view> -->
              </view>
              <view style="width:200rpx;">
                <ai-progress :percentage="(eleObjs.customerSignatureCount / eleObjs.planTaskCount * 100)"
                             :isCount="(eleObjs.customerSignatureCount || 0) + '/' + (eleObjs.planTaskCount || 0)"
                             :strokeWidth="6" inBgColor="#DCF0FF" bgColor="#0091FF">
                </ai-progress>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="tips" v-if="buildingList.length && !mainPlan">
        共
        <text>{{ total }}</text>
        个
      </view>

      <view class="content" v-if="buildingList.length"><list-card v-for="(item, index) in buildingList"
                                                                  :key="index" :msg="item" :mainPlan="mainPlan" @toDetail="toDetail"></list-card></view>
      <view v-show="isLoadMore"><uni-load-more :status="loadStatus"></uni-load-more></view>

      <view class="empty" v-if="!buildingList.length">
        <view class="circle">
          <image src="/static/images/emptyS.png" mode=""></image>
        </view>

        <view class="title">暂无搜索结果</view>
        <view class="tips">可以更换搜索条件试试</view>
      </view>

      <time-select v-if="selectTimePopup" @close="closeSelectTimePopup"></time-select>
    </view>
  </scroll-view>
</template>

<script>
import Header from '../../pages/index/components/header.vue';
import timeSelect from '../../pages/index/components/timeSelect.vue';
import aiprogress from '@/components/ai-progress/ai-progress.vue';
import UniLoadMore from '@/components/uni-load-more/uni-load-more';
import ListCard from './components/listCard.vue';
import { getMonthDate, formatTime, hanleToken, removeEmpty, debounce } from '@/utils/utils.js';
import { getRepairCheck, getRepairScore, getGroundCount } from '@/apis/statistic.js';
import { calendarlistStatistics } from '@/apis/maintains.js';
import filterModel from './components/test.vue';
import { getLastDates } from '@/utils/tools.js';
import { mapState, mapActions } from 'vuex';

export default {
	components: {
		Header,
		timeSelect,
		ListCard,
		filterModel,
		UniLoadMore,
		aiprogress
	},
	data() {
		return {
			customDate: '',
			headerIndex: 0,
			selectTimePopup: false,
			searchTypes: 1,
			beginTime: '',
			endTime: '',
			filterList: [
				{
					id: 1,
					name: '今日'
				},
				{
					id: 2,
					name: '近7天'
				},
				{
					id: 3,
					name: '近30天'
				},
				{
					id: 4,
					name: '自定义'
				}
			],
			showFilter: false,
			obj: {
				keyword: '',
				size: 10,
				current: 1,
				userIds: ''
			},
			conditionsParams: {
				planStatus: '',
				timeliness: '',
				duration: '',
				sign: ''
			},
			buildingList: [],
			allFilter: true,
			csd: {},
			formatTime: formatTime,
			getMonthDate: getMonthDate,
			total: 0,
			loadStatus: 'loading', // 加载样式：more-加载前样式，loading-加载中样式，noMore-没有数据样式
			isLoadMore: false,
			pageHight: uni.getSystemInfoSync().windowHeight + 10,
			scoreState: 0,
			mainPlan: 0,// 保养计划月历
			eleObjs: {},// 保养计划t统计数据
			isTipsOne: false,
			isTipsTwo: false,
			buildingId: '',
			elevatorIds: [],
		};
	},
	watch: {
		isTipsOne: {
			handler(val) {
				// this.$emit('handchange',val)
				console.log('valval', val);
				this.isTipsOne = val;
				// this.$emit('update:visible', val)
			},
			immediate: true,
		},
	},
	async onLoad(e) {
		await this.handleRreshToken();
		if (!this.userinfo.user_id) {
			uni.showModal({
				title: '提示',
				content: '检测到您未登录或登录已失效，请前往登录后在操作',
				showCancel: false,
				success: () => {
					uni.navigateTo({
						url: '../login/index'
					});
				}
			});
			return;
		}
		console.log('eeeeeeee', e);
		if (Number(e.mainPlan) == 1) {
			// 保养计划月历进来
			this.mainPlan = Number(e.mainPlan);
			this.customDate = e.planTimes || '';
			this.buildingId = e.buildingId || '';
			this.beginTime = e.planTimes;
			this.endTime = e.planTimes;
			this.elevatorIds = JSON.parse(e.eleIds);
			let arr = hanleToken('get', 'elevatorIdAll');
			if (this.elevatorIds && this.elevatorIds.length) {
				arr = this.elevatorIds;
			}

			this.initListStatistics(arr, e.planTimes, e.planTimes);
		}

		if (Number(e.scoreState) == 1) {
			// 小程序模板消息进来
			this.scoreState = Number(e.scoreState);
			this.beginTime = e.startTime;
			this.endTime = e.endTime;
		}
		if (e.data) {
			const data = JSON.parse(e.data);
			// console.log(data,"跳转页面的data")
			const { value, startTime, endTime, scoreState } = data;
			// console.log("跳转搜索",data)
			this.scoreState = Number(scoreState);
			if (data.value) {
				this.obj[data.key] = data.value.join(',');
			}
			if (data.key == 'timeliness') {
				this.conditionsParams.timeliness = data.value.join(',');
			}
			this.allFilter = false;
			this.csd[`${data.key}`] = data.value;
			if (data.tabNums) {
				// 处理年审梯选中
				this.csd.useType = data.tabNums;
				this.obj.useType = data.tabNums[0];
			}
			if (startTime) {
				this.headerIndex = data.dateType ? data.dateType - 1 : 3;
				this.beginTime = startTime;
				this.endTime = endTime;
				if ((data.dateType && data.dateType == 4) || !data.dateType) {
					this.customDate = startTime.slice(5) + '~' + endTime.slice(5);
				}
			}
			const res = uni.getStorageSync('statistical' + (data.childDeep ? data.childDeep : ''));
			if (res) {
				this.obj.userIds = res.id;
			}
			this.initList();
      
			// 存在IOS不回调的问题，改用同步方式实现
			// uni.getStorage({
			// key: 'statistical' + (data.childDeep ? data.childDeep : ''),
			// success: res => {
			// console.log(res, '列表获取缓存的值');
			// // this.userList = res.data.id.split(',');
			// this.obj.userIds = res.data.id;
			// this.initList();
			// }
			// });

			// 如果是个人
			// if(data.isPersonal){
			// 	console.log("个人版");

			// }else{
			// 	uni.getStorage({
			// 		key: 'statistical',
			// 		success: res => {

			// 			this.obj.userIds = res.data.id;
			// 			this.initList()

			// 		}
			// 	});

			// }
			// this.showFilter = true;

			// setTimeout(() => {
			// 	this.getList();
			// }, 500);
		} else {
			const res = uni.getStorageSync('statistical');
			if (res) {
				this.obj.userIds = res.id;
			}
			this.initList();
			//  存在IOS不回调的问题，改用同步方式实现
			// uni.getStorage({
			// key: 'statistical',
			// success: res => {
			// this.obj.userIds = res.data.id;
			// this.initList();
			// }
			// });
		}
	},

	computed: {
		...mapState('user', ['userinfo'])
	},
	created() {
		// 创建防抖版本的handleReSet方法
		this.debouncedHandleReSet = debounce(this._handleReSet, 500);
	},
	onShow() {
		// this.getList()
	},

	methods: {
		...mapActions('user', ['handleRreshToken']),
		scrollEvent(e) {
			if (this.mainPlan) {
				uni.$emit('tooltipsClose');
			}
		},

		// 保养月历统计明细
		initListStatistics(elevatorIds, startDate, endDate) {
			calendarlistStatistics(removeEmpty({
				elevatorIds,
				startDate,
				endDate,
			})).then(res => {
				console.log('initListStatistics', res);
				if (res.code === 200) {
					this.eleObjs = res.data || {};
				}
			});
		},
		initList() {
			this.showFilter = true;
			this.getList();
			// setTimeout(() => {
			// 	this.getList();
			// }, 500);
		},
		getList() {
			uni.showLoading({
				title: '数据加载中'
			});
			const params = {
				startTime: this.beginTime || formatTime(getMonthDate().startDate),
				endTime: this.endTime || formatTime(getMonthDate().endDate),
				buildingId: this.buildingId,
				elevatorIds: this.elevatorIds,
				...this.obj
			};
			if (this.elevatorIds && this.elevatorIds.length) {
				params.elevatorIds = this.elevatorIds;
			}
			let promises;
			if (this.scoreState === 1) {
				let obj = {
					startTime: this.beginTime || formatTime(getMonthDate().startDate),
					endTime: this.endTime || formatTime(getMonthDate().endDate),
					userIds: this.obj.userIds,
					size: this.obj.size,
					current: this.obj.current,
					buildingId: this.buildingId,
				};
				if (this.elevatorIds && this.elevatorIds.length) {
					obj.elevatorIds = this.elevatorIds;
				}
				promises = getRepairScore(obj);
			} else {
				promises = getRepairCheck(params);
			}
			console.log('this.scoreState', this.scoreState);
			promises.then(res => {
				console.log('promises', res);
				if (res) {
					uni.hideLoading();
					this.buildingList = this.buildingList.concat(res.data.records);
					this.total = res.data.total;
					if (res.data.records.length < this.obj.size) {
						// console.log(res.data.records.length, this.obj.size, 111);
						this.isLoadMore = true;
						this.loadStatus = 'noMore';
					} else {
						this.isLoadMore = false;
					}
					// uni.hideLoading();
					// this.buildingList=res.data.records
					// this.total=res.data.total
				} else {
					uni.showToast({ title: '请求失败', icon: 'none' });
					this.isLoadMore = false;
					if (this.obj.current > 1) {
						this.obj.current -= 1;
					}
				}
			});
		},

		// getConditionsParams(arr) {
		// 	let newList = [];
		// 	arr.forEach(item => {
		// 		let newName = newList.find(i => i.key == item.key);
		// 		if (!newName) {
		// 			newList.push({ key: item.key, value: [item.value] });
		// 		} else {
		// 			newName.value.push(item.value);
		// 		}
		// 	});
		// 	newList.forEach(item => {
		// 		if (this.conditionsParams.hasOwnProperty(item.key)) {
		// 			this.conditionsParams[item.key] = item.value.join(',');
		// 		}
		// 	});
		// },

		// 切换顶部日期筛选
		filterFuc(type) {
			console.log('切换顶部', type);
			if (type.id == 4) {
				this.selectTimePopup = true;
			} else {
				this.customDate = '';

				if (type.id == 1) {
					// 今天
					const dates = getLastDates(0);
					this.beginTime = dates.startTime;
					this.endTime = dates.endTime;
				}
				if (type.id == 2) {
					// 近七天
					const dates = getLastDates(7, false);
					this.beginTime = dates.startTime;
					this.endTime = dates.endTime;
				}
				if (type.id == 3) {
					// 近30天
					const dates = getLastDates(30, false);
					this.beginTime = dates.startTime;
					this.endTime = dates.endTime;
				}

				this.obj.current = 1;
				this.buildingList = [];
				this.getList();
			}
		},
		closeSelectTimePopup(val) {
			// 如果选择了日期
			if (val) {
				if (val.includes('-')) {
					let ary = val.split('-');
					let start = ary[0].replaceAll('.', '-');
					let end = ary[1].replaceAll('.', '-');
					this.beginTime = start;
					this.endTime = end;
					this.customDate = start.slice(5) + '~' + end.slice(5);
				} else {
					const time = val.replaceAll('.', '-');
					this.beginTime = time;
					this.endTime = time;
					this.customDate = time;
				}

				// this.customDate = start+ '~' + end;
				// 自定义筛查接口
				// this.filterTime(start, end);
				// 触发headername的改变
				this.obj.current = 1;
				this.buildingList = [];
				this.getList();
			} else {
				// 日期取消操作
			}
			this.selectTimePopup = false;
		},
		// 筛选
		filterd(res) {
			console.log(res, '最外层父组件接受确定');
			this.obj.current = 1;
			this.totalPage = 0;
			if (res.allChecked) {
				this.obj.allChecked = true;
				if (this.obj.planStatus != undefined) {
					delete this.obj.planStatus;
				}
				if (this.obj.timeliness != undefined) {
					delete this.obj.timeliness;
				}
				if (this.obj.sign != undefined) {
					delete this.obj.sign;
				}
				if (this.obj.duration != undefined) {
					delete this.obj.duration;
				}
				if (this.obj.useType != undefined) {
					delete this.obj.useType;
				}
				if (this.obj.overdue != undefined) {
					delete this.obj.overdue;
				}
				// this.initElevatorGroup();
				// this.initStatistics()
				this.buildingList = [];
				this.getList();
				return;
			}
			this.obj.allChecked = false;
			if (res.choosed.planStatus) {
				this.obj.planStatus = res.choosed.planStatus.join(',');
			}
			if (res.choosed.timeliness) {
				this.obj.timeliness = res.choosed.timeliness.join(',');
			}
			if (res.choosed.overdue) {
				this.obj.overdue = res.choosed.overdue.join(',');
			}
			if (res.choosed.sign) {
				this.obj.sign = res.choosed.sign.join(',');
			}
			if (res.choosed.duration) {
				this.obj.duration = res.choosed.duration.join(',');
			}
			if (res.choosed.useType) {
				this.obj.useType = res.choosed.useType.join(',');
				if (res.choosed.useType.length === 2) {
					delete this.obj.useType;
				}
			}

			this.buildingList = [];
			this.obj.current = 1;
			this.getList();
		},
		// showFilterContent() {
		// 	this.$refs.filterContent.open();
		// 	this.showFilter = true;
		// },
		handleConfirm(res) {
			this.conditionsList = res;
			this.$refs.filterContent.close();
			this.showFilter = false;
		},

		// 点击返回
		handleBack() {
			// console.log('点击返回按钮');
			uni.navigateBack({});
		},
		// onReachBottom() {
		// 	console.log('下拉加载', this.obj.current);
		// 	if (!this.isLoadMore) {
		// 		//此处判断，上锁，防止重复请求
		// 		this.isLoadMore = true;
		// 		this.obj.current += 1;
		// 		this.getList()
		// 	}
		// },
		onPullDownRefresh() {
			this.obj.current = 1;
			this.buildingList = [];
			this.getList();
			setTimeout(function () {
				uni.stopPullDownRefresh(); // 停止下拉刷新动画
			}, 1000);
		},
		scrolltolower() {
			console.log('aaaaaaaaaaaaaa');
			// this.showData = true;
			// if (this.obj.current < this.totalPage) {
			// 	this.obj.current += 1;
			// 	this.initElevatorGroup(this.groupLeader);
			// } else {
			// 	this.state = 'noMore';
			// }
			if (!this.isLoadMore) {
				// 此处判断，上锁，防止重复请求
				this.isLoadMore = true;
				this.obj.current += 1;
				this.getList();
			}
		},
		toDetail(item) {
			// 保养详情
			let planCheckName = item.planCheckName;
			let overdueName = item.overdueName;
			uni.navigateTo({
				url: `/subpages/workOrders/detail?planId=${item.planId}&elevatorId=${item.elevatorId}&planCheckName=${planCheckName}&overdueName=${overdueName}`
			});
		},
		// 重置条件
		_handleReSet(args) {
			// 实际执行查询的方法
			console.log(args, 'e的值');
			// this.seachForm.keyword=e.detail.value
			this.buildingList = [];
			this.obj.current = 1;
			this.obj.total = 0;
			this.getList();
		},
		// 对外暴露的防抖处理方法
		handleReSet(e) {
			// 调用防抖后的方法
			this.debouncedHandleReSet(e);
		},
		handlerClick() {
			uni.$emit('tooltipsClose');
		}
	}
};
</script>

<style lang="scss" scoped>
.maintenanceStatistics {
  background-color: #f3f6f8;

  .head {
    width: 100%;
    position: sticky;
    top: 0;
    left: 0;
    z-index: 99;
    background-color: #fff;

    .left {
      // width: 600rpx;
      // height: 64rpx;
      // box-sizing: border-box;
      // background: #f6f6f6;
      border-radius: 8rpx;
      display: flex;
      align-items: center;
      padding: 20rpx;
      border-bottom: 2rpx solid #eee;

      /deep/ .uni-searchbar {
        padding: 0;
      }

      /deep/ .uni-searchbar__box {
        width: 600rpx;
        height: 64rpx;
        justify-content: flex-start;
        font-size: 26rpx;
        color: #ccc;
        background-color: #f6f6f6;
        border: 0;
        border-radius: 8rpx;
      }

      /deep/ .uni-icons {
        width: 40rpx;
        height: 40rpx;
      }

      /deep/ .uni-searchbar__text-placeholder {
        margin: 0;
      }

      /deep/ .uni-searchbar__box-search-input {
        border: 0;
        padding: 0;
      }

      input {
        font-size: 26rpx;
        height: 36rpx;
        padding-left: 28rpx;
        width: 600rpx !important;
        box-sizing: border-box;
        // padding: ;
      }

      image {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }

  .setp {
    padding: 20rpx;
    background: #fff;
    margin-bottom: 20rpx;
    border-top: 2rpx #eee solid;
    border-bottom: 2rpx #eee solid;

    .setp_cont {
      font-size: 24rpx;
      color: #999999;
      margin-bottom: 20rpx;
    }

    .setp_LR {
      display: flex;
      position: relative;

      .L_text {
        display: flex;
        flex: 0 0 330rpx;
        align-items: center;

      }

      .R_text {
        flex: 1;
        display: flex;
        align-items: center;
      }

      .text_tit {
        font-size: 24rpx;
        color: #666666;
      }

      .tipsr {
        .tips_text {
          display: block;
          z-index: 1;
          position: absolute;
          left: 30rpx;
          background-color: #333;
          border-radius: 8px;
          color: #fff;
          margin-top: 10rpx;
          font-size: 26rpx;
          text-align: left;
          line-height: 16rpx;
          padding: 20rpx;
        }
      }
    }

  }

  .search {
    display: flex;
    padding: 10rpx 0;
    background: #ffffff;
    display: flex;
    // position: sticky;
    // z-index: 999;
    top: 107rpx;
    left: 0;
    right: 0;
    position: sticky;
    top: 0;
    left: 0;
    z-index: 99;

    image {
      width: 22rpx;
      height: 22rpx;
      transition: 0.3s all;
      margin: 4rpx 0rpx 0 7rpx;
    }

    .name {
      display: flex;
      font-size: 26rpx;
      color: #333;
      border-right: 1rpx solid #ccc;
      font-weight: 500;
      align-items: center;
      padding-right: 16rpx;
      padding-left: 20rpx;
      margin: 10rpx 0;
    }

    .searchContent {
      display: flex;
      flex: 1;
      padding-left: 26rpx;
      flex-wrap: wrap;
      padding-bottom: 10rpx;
    }

    .searchItem {
      padding: 0 10rpx;
      margin-top: 10rpx;
      color: #666;
      border: 2rpx solid #cccccc;
      border-radius: 4rpx;
      margin-right: 16rpx;
      font-size: 24rpx;
      display: flex;
      align-items: center;
    }
  }

  .tips {
    padding: 20rpx 0 20rpx 40rpx;
    font-size: 24rpx;
    color: #999999;

    text {
      color: #0091ff;
    }
  }

  .content {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    z-index: 100;

    .contentItem {}
  }

  .empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 100rpx;
    width: 100%;
    height: 600rpx;

    .circle {
      width: 112rpx;
      height: 112rpx;
      border-radius: 50%;
    }

    image {
      width: 112rpx;
      height: 112rpx;
    }

    .title {
      font-size: 28rpx;
      color: #666;
      font-weight: 400;
      margin-top: 10rpx;
    }

    .tips {
      font-size: 24rpx;
      color: #999;
    }
  }
}
</style>
